package com.yx.frame.jdbc.pool;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;

public final class PConnection {
	private Connection conn;
	private String jndiName = "";
	boolean inUse = false;
	int useCount = 0;
	long lastAccess = 0;	
	boolean isFramePool=true;

	protected PConnection(String jndiName,String dbDriver, String dbUrl, String dbUser,
			String dbPassword) throws Exception {
		this.jndiName=jndiName;
		connect(dbDriver, dbUrl, dbUser, dbPassword);
		isFramePool=true;
	}

	protected PConnection(Connection conn) {
		this.conn = conn;
		lastAccess = System.currentTimeMillis();
		isFramePool=false;
	}

	public Connection getConnection() {
		return conn;
	}

	public boolean isConnected() {
		try {
			if (!this.conn.isClosed()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	private void connect(String dbDriver, String dbUrl, String dbUser,
			String dbPassword) throws Exception {
		Connection c = null;
		try {
			Driver oracleDriver = (Driver) Class.forName(dbDriver)
					.newInstance();
			DriverManager.registerDriver((Driver) oracleDriver);
			c = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
		} catch (Exception e) {
			throw new Exception("连接数据库失败:" + e.toString());
		}
		this.conn = c;
	}

	public boolean isInUse() {
		return inUse;
	}

	public int getUseCount() {
		return useCount;
	}

	public long getlastAccessTime() {
		return lastAccess;
	}

	protected void disConnect() {
		try {
			conn.close();
		} catch (Exception e) {
		}
	}
	public void close(){
		if(isFramePool){
			try {
				PoolManager.getInstance().freeFramePoolConnection(jndiName, this);
			} catch (Exception e) {
			}
		}else{
			try {
				conn.close();
				conn = null;
			} catch (Exception e) {
			}
		}
	}	
}
